package com.atguigu.gmall.payment.service.impl;

import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.model.enums.PaymentStatus;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.payment.mapper.PaymentInfoMapper;
import com.atguigu.gmall.payment.service.PaymentService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service
public class PaymentServiceImpl implements PaymentService {

    @Autowired
    private PaymentInfoMapper paymentInfoMapper;
    @Autowired
    private RabbitService rabbitService;

    //根据传来的orderInfo订单对象，以及支付类型，保存支付（对象）信息
    @Override
    public void savePayment(OrderInfo orderInfo, String paymentType) {
        //查询是否该订单对应同种支付类型已经保存过，
        QueryWrapper<PaymentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id",orderInfo.getId());
        queryWrapper.eq("payment_type", paymentType);
        Integer count = paymentInfoMapper.selectCount(queryWrapper);
        if(count > 0) {
            return;
        }
        //封装支付信息数据
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setOutTradeNo(orderInfo.getOutTradeNo());
        paymentInfo.setOrderId(orderInfo.getId());
        paymentInfo.setPaymentType(paymentType);
        paymentInfo.setTotalAmount(orderInfo.getTotalAmount());
        paymentInfo.setSubject(orderInfo.getTradeBody());
        paymentInfo.setPaymentStatus(PaymentStatus.UNPAID.name());
        paymentInfo.setCreateTime(new Date());

        paymentInfoMapper.insert(paymentInfo);

    }

    @Override
    public PaymentInfo getPaymentInfo(String outTradeNo, String payTypeName) {
        //  直接写
        QueryWrapper<PaymentInfo> paymentInfoQueryWrapper = new QueryWrapper<>();
        paymentInfoQueryWrapper.eq("out_trade_no",outTradeNo);
        paymentInfoQueryWrapper.eq("payment_type",payTypeName);
        return paymentInfoMapper.selectOne(paymentInfoQueryWrapper);
    }

    @Override
    public void paySuccess(String outTradeNo, String payTypeName, Map<String, String> paramMap) {
        //根据out_trade_no以及支付类型（alipay）查询支付信息
        PaymentInfo paymentInfoQuery = this.getPaymentInfo(outTradeNo, payTypeName);
        if (paymentInfoQuery == null || "CLOSED".equals(paymentInfoQuery.getPaymentStatus())
                || "PAID".equals(paymentInfoQuery.getPaymentStatus())){
            return;
        }
        //  trade_no , payment_status,callback_time,callback_content
        //  第一个参数：更新的内容！ 第二个参数更新的条件
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setTradeNo(paramMap.get("trade_no"));
        paymentInfo.setPaymentStatus(PaymentStatus.PAID.name());
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setCallbackContent(paramMap.toString());

        this.updatePaymentInfo(outTradeNo,payTypeName,paymentInfo);

        //利用rabbitMQ发送消息，更改订单状态
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_PAYMENT_PAY,MqConst.ROUTING_PAYMENT_PAY,paymentInfoQuery.getOrderId());

    }

    //更新支付信息
    @Override
    public void updatePaymentInfo(String outTradeNo, String payTypeName, PaymentInfo paymentInfo) {
        UpdateWrapper<PaymentInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("out_trade_no",outTradeNo);
        updateWrapper.eq("payment_type",payTypeName);
        //  更新数据
        paymentInfoMapper.update(paymentInfo,updateWrapper);
    }

    //根据订单id 关闭交易信息 ，即状态改为Closed
    @Override
    public void closePayment(Long orderId) {
        QueryWrapper<PaymentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        Integer count = paymentInfoMapper.selectCount(queryWrapper);
        if (count == 0){
            return;
        }
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setPaymentStatus(PaymentStatus.CLOSED.name());

        paymentInfoMapper.update(paymentInfo,queryWrapper);
    }
}
